#!/usr/bin/env python
# encoding: utf-8

"""
    1. 获取所有报表的指标，并且整理到指定表(指标名称, 使用率)
"""

from source.Lib import orm


@orm.SQL("Insert")
def InitAllReportQuota(db):
    db.query(orm.ReportQuota).delete()

    QuotaCodes = dict()
    codes = set()
    for report in db.query(orm.Report).all():
        codes.add(report.code)
        for k in report.financial:
            QuotaCodes.setdefault(k, set())
            QuotaCodes[k].add(report.code)

    lInsert = list()
    for quota in QuotaCodes:
        coverage = round(len(QuotaCodes[quota])/len(codes)*100, 2)
        lInsert.append(orm.ReportQuota(name=quota, codes=list(QuotaCodes[quota]), coverage=coverage))

    return lInsert


@orm.SQL("Insert")
def InitAllIndustry(db):
    db.query(orm.Industry).delete()

    dtCodeIndustry = dict()
    for stock in db.query(orm.StockInfo).all():
        for industry in stock.profession:
            dtCodeIndustry.setdefault(industry, list())
            dtCodeIndustry[industry].append(stock.code)

    lInsert = list()
    for industry in dtCodeIndustry:
        lInsert.append(orm.Industry(name=industry, codes=dtCodeIndustry[industry]))

    return lInsert


if __name__ == "__main__":
    InitAllReportQuota()
    InitAllIndustry()
